package com.showsu.editor.utils.remote;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.showsu.editor.entity.remote.VideoDetailResult;
import com.showsu.editor.entity.remote.WhoseCardVideoDetailResp;
import com.showsu.editor.entity.remote.apiok.ApiOkBaseResult;
import com.showsu.editor.entity.remote.apiok.ApiOkDyAwemeDetailResult;
import com.showsu.editor.enums.SuccessEnum;
import com.showsu.editor.service.IRemoteInterfaceRecordService;
import com.showsu.editor.service.IRemoteInterfaceWarnSmsRecordService;
import com.showsu.editor.utils.RetryUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.concurrent.Callable;

/**
 * @Author: jph
 * @Description:
 * @Date: Created in 16:23 下午 2024/09/11
 * @Modified By:
 */
@Slf4j
@Component
public class ApiOkUtil {

    @Value("${apiok.url}")
    private String apiUrl;

    @Value("${apiok.token}")
    private String token;

    private static final int timeout = 15000;
    private static final int timeout25 = 25000;

    /**
     * 最多重试次数
     */
    private static final int RETRY_MAX_COUNT = 3;

    /**
     * 重试等待间隔
     */
    private static final int RETRY_WAIT_TIME = 1500;

    @Autowired
    private IRemoteInterfaceRecordService remoteInterfaceRecordService;

    @Autowired
    private IRemoteInterfaceWarnSmsRecordService remoteInterfaceWarnSmsRecordService;

    /**
     * 获取dy作品详情
     * @param awemeId 作品id
     * @return
     */
    public WhoseCardVideoDetailResp getDyAwemeDetail(String awemeId, Long interfaceId) {
        if (StringUtils.isBlank(awemeId)) {
            return null;
        }
        WhoseCardVideoDetailResp result = new WhoseCardVideoDetailResp();
        String response = RetryUtils.retry(new Callable<String>() {
            @Override
            public String call() {
                try {
                    long start = System.currentTimeMillis();
                    StringBuilder url = new StringBuilder(apiUrl).append("/api/e5f8/post/detail/v1?apikey=").append(token).append("&aweme_id=").append(awemeId);
                    String responseInner = HttpUtil.get(url.toString(), timeout);
                    log.info("ApiOkUtil 查询dy作品详情数据-响应耗时:{}", System.currentTimeMillis() - start);
                    ApiOkBaseResult temp = JSON.parseObject(responseInner, ApiOkBaseResult.class);
                    //如果平台那边报错再重试一次
                    if (temp == null || temp.getCode() != null && temp.getCode() != 0) {
                        remoteInterfaceRecordService.add(interfaceId, SuccessEnum.FAIL.getCode());
                        return "";
                    }
                    remoteInterfaceRecordService.add(interfaceId, SuccessEnum.SUCCESS.getCode());
                    return responseInner;
                } catch (Exception e) {
                    remoteInterfaceRecordService.add(interfaceId, SuccessEnum.FAIL.getCode());
                    log.error("ApiOkUtil getDyAwemeDetail(String, Long) error, awemeId:{}, interfaceId:{}, e:{}", awemeId, interfaceId, e);
                    return "";
                }
            }
        }, RETRY_MAX_COUNT, RETRY_WAIT_TIME);
        if (StringUtils.isBlank(response)) {
            remoteInterfaceWarnSmsRecordService.sendWarnSmsIn15mins(interfaceId,
                    new StringBuilder("awemeId=").append(awemeId).toString());
            return result;
        }
        try {
            ApiOkDyAwemeDetailResult originResult = JSON.parseObject(response, ApiOkDyAwemeDetailResult.class);
            VideoDetailResult videoDetailResult = new VideoDetailResult();
            if(originResult.getResult()!=null){
                videoDetailResult.setAweme_detail(originResult.getResult().getAweme_detail());
            }
            result.setResult(videoDetailResult);
        } catch (Exception e) {
            log.error("MoreAPIProUtil.getDyAwemeDetail(String, Long) convert error, awemeId:{}, interfaceId:{}, e:{}", awemeId, interfaceId, e);
        }
        return result;
    }
    public static void main(String[] args) {
    }
}
